package git.soulbgm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import git.soulbgm.pojo.AlarmRuleInfo;
import git.soulbgm.service.AlarmRuleInfoService;
import git.soulbgm.mapper.AlarmRuleInfoMapper;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 告警规则信息表
 *
 * @author SoulBGM
 * @date 2020-11-18 10:03:05
 */
@Service
public class AlarmRuleInfoServiceImpl extends ServiceImpl<AlarmRuleInfoMapper, AlarmRuleInfo> implements AlarmRuleInfoService {

    /**
     * Cacheable
     * value：缓存key的前缀。
     * key：缓存key的后缀。
     * sync：设置如果缓存过期是不是只放一个请求去请求数据库，其他请求阻塞，默认是false。
     */
    @Cacheable(value = "alarmRuleTypeAndTriggering", key = "#ruleType+'-'+#eventCode", sync = true)
    @Override
    public List<AlarmRuleInfo> findByRuleTypeAndEventCode(String ruleType, String eventCode) {
        LambdaQueryWrapper<AlarmRuleInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper
                .eq(AlarmRuleInfo::getRuleType, ruleType)
                .eq(AlarmRuleInfo::getEventCode, eventCode)
                .orderByDesc(AlarmRuleInfo::getThreshold);
        return list(wrapper);
    }

    @Override
    public List<AlarmRuleInfo> findByRuleType(String ruleType) {
        LambdaQueryWrapper<AlarmRuleInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper
                .eq(AlarmRuleInfo::getRuleType, ruleType)
                .orderByAsc(AlarmRuleInfo::getEventCode)
                .orderByDesc(AlarmRuleInfo::getThreshold);
        return list(wrapper);
    }

    @Cacheable(value = "alarmRuleMap", key = "#ruleType", sync = true)
    @Override
    public Map<String, List<Double>> getAlarmRuleMap(String ruleType) {
        List<AlarmRuleInfo> infoList = findByRuleType(ruleType);
        return infoList.stream().collect(Collectors.toMap(AlarmRuleInfo::getEventCode, o -> {
            List<Double> values = new ArrayList<>();
            values.add(o.getThreshold());
            return values;
        }, (old, xin) -> {
            old.addAll(xin);
            return old;
        }));
    }

    @CacheEvict(value = {"alarmRuleTypeAndTriggering", "alarmRuleType"}, allEntries = true)
    @Override
    public void clearCache() {
    }


}